package com.lc202309;

import java.util.*;

/**
 * Description:
 *
 * @Create 2023/9/24 22:33
 * @Version 1.0
 */
public class LRUCache {
    private LinkedHashSet<Integer> set;
    private Map<Integer, Integer> map;
    private int capacity;

    public LRUCache(int capacity) {
        this.set = new LinkedHashSet<>(capacity);
        this.map = new HashMap<>(capacity);
        this.capacity = capacity;
    }

    public int get(int key) {
        int res = map.getOrDefault(key, -1);
        if (res != -1) {
            set.remove(key);
            set.add(key);
        }
        return res;
    }

    public void put(int key, int value) {
        if (set.contains(key)) {
            set.remove(key);
            set.add(key);
            map.put(key, value);
            return;
        }
        if (set.size() == capacity) {
            Integer tmp = set.iterator().next();
            set.remove(tmp);
            map.remove(tmp);
        }
        set.add(key);
        map.put(key, value);
    }

    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(2);
        lruCache.put(1, 1);
        lruCache.put(2, 2);
        lruCache.get(1);
        lruCache.put(3, 3);
        lruCache.get(2);
        lruCache.put(4, 4);
        lruCache.get(1);
        lruCache.get(3);
        lruCache.get(4);
    }
}
